/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.regex.Pattern;

import junit.framework.TestCase;


/**
 * Performs Validation Test for url validations.
 * 
 * @version $Revision: 1128446 $ $Date: 2011-05-27 13:29:27 -0700 (Fri, 27 May
 *          2011) $
 */
public class UrlValidatorTest extends TestCase {

	private boolean printStatus = false;
	private boolean printIndex = false;// print index that indicates current
										// scheme,host,port,path, query test
										// were using.
	UrlValidator urlVal = new UrlValidator(null, null,
			UrlValidator.ALLOW_ALL_SCHEMES);

	public UrlValidatorTest(String testName) {
		super(testName);
	}

	public boolean manualTestUrl(String testurl, boolean truthValue) {

		System.out.print(testurl);
		System.out.print(" returned as ");
		if (urlVal.isValid(testurl) == truthValue) {
			System.out.print(truthValue);
			System.out.print(": Passed ");
			System.out.println();
			return true;
		} else {
			System.out.print(truthValue);
			System.out.print(": Failed ");
			System.out.println();
			return false;
		}

	}

	public void testManualTest() {

		System.out.println("Manual Testing Results: ");

		
		assertTrue(manualTestUrl("http://www.amazon.com", true));
		assertTrue(manualTestUrl("http://www.google.com", true));
		assertTrue(manualTestUrl("http://www.abc.comm", false));
		assertTrue(manualTestUrl("http://wwww.amazon.com", false));
		assertTrue(manualTestUrl("http:///oregonstate.edu", false));

		System.out.println();
	}

	public void testYourFirstPartition() {
		System.out.println("First Partition Test Results: ");

		assertTrue(manualTestUrl("http://www.ebay.com", true));
		assertTrue(manualTestUrl("http://0.0.0.0.com", true));
		assertTrue(manualTestUrl("http://www.uprightbrewing.com/bottles.html", true));
		assertTrue(manualTestUrl("http://flyboybeer.com/whats-tap/", true));
		assertTrue(manualTestUrl("http://www.block15.com/news", true));
		assertTrue(manualTestUrl("http://i.imgur.com/YFWYf46.jpg", true));
		assertTrue(manualTestUrl(
				"http://www.reddit.com/r/askscience/comments/2emhlm/how_long_does_screen_burn_on_a_plasma_actually/",
				true));
		assertTrue(manualTestUrl(
				"http://www.ebay.com/sch/i.html?_from=R40&_trksid=p2051541.m570.l1313.TR10.TRC0.A0.H0.Xshirts&_nkw=shirts&_sacat=11450",
				true));
		assertTrue(manualTestUrl("https://ninite.com/", true));
		assertTrue(manualTestUrl(
				"http://search.oregonstate.edu/index.php?q=people+and+things&site=All&client=default_frontend&btnG=Search",
				true));

		System.out.println();
	}

	public void testYourSecondPartition() {
		System.out.println("Second Partition Test Results: ");

		assertTrue(manualTestUrl(
				"ht3tp://knowyourmeme.com/memes/popular/page/19?custom_macro=OIQ_ADNETUUID%25255E4d860d0f-7e3e-4f3e-954a-1895562b811b%25255EAUCTION_DATE%25255E2012-07-05",
				false));
		assertTrue(manualTestUrl(
				"https/my.oregonstate.edu/webapps/portal/frameset.jsp?tab_tab_group_id=_2_1&url=%2Fwebapps%2Fblackboard%2Fexecute%2Flauncher%3Ftype%3DCourse%26id%3D394421%26url%3Dl",
				false));

		System.out.println();
	}

	public void testYourThirdPartition() {
		System.out.println("Thrid Partition Test Results: ");

		assertTrue(manualTestUrl("www.bk.9", false));
		assertTrue(manualTestUrl("www.mcdonalds.7345/us/en/home.html", false));

		System.out.println();
	}

	public void testYourFourthPartition() {
		System.out.println("Fourth Partition Test Results: ");

		assertTrue(manualTestUrl("www.mcdonalds.7345/us/en/home.html", false));
		assertTrue(manualTestUrl(
				"https://www.playdominion.com:34828/Dominion/gameClient.html",
				false));

		System.out.println();
	}

	public void testYourFifthPartition() {
		System.out.println("Fifth Partition Test Results: ");

		assertTrue(manualTestUrl("http://thepiratebay.se/test1//abc", false));
		assertTrue(manualTestUrl("https://ninite.com/../", false));

		System.out.println();
	}

	public void testYourSixthPartition() {
		System.out.println("Sixth Partition Test Results: ");

		assertTrue(manualTestUrl("htt//ww.256.256.256.26:427/index?action=stuff", false));
		assertTrue(manualTestUrl("htps:/w.amazron.moc:23478/undex?why=cuzisaidso", false));

		System.out.println();
	}

	public boolean callIsValidQuery(String testurl, boolean truthValue) {

		System.out.print(testurl);
		System.out.print(" returned as ");
		if (urlVal.isValidQuery(testurl) == truthValue) {
			System.out.print(truthValue);
			System.out.print(": Passed ");
			System.out.println();
			return true;
		} else {
			System.out.print(truthValue);
			System.out.print(": Failed ");
			System.out.println();
			return false;
		}
	}

	public void testIsValidQuery() {
		
		System.out.println("Testing isValidQuery(): ");


		assertTrue(callIsValidQuery("http://www.google.com/?action=view", true));
		assertTrue(callIsValidQuery("http://www.google.com/?action=eidt&mode=up", true));
		assertTrue(callIsValidQuery("http://www.google.com/", true));
		
		System.out.println();

	}
	
	public boolean callPortNumber(String myport, boolean truthValue) {

	    
		final String PORT_REGEX = "^:(\\d{1,3})$";
		final Pattern PORT_PATTERN = Pattern.compile(PORT_REGEX);
		    

		System.out.print(myport);
		System.out.print(" returned as ");
		
        if(!PORT_PATTERN.matcher(myport).matches()) {
			System.out.print(truthValue);
			System.out.print(": Failed ");
			System.out.println();	
            return false;
        }	
        
		System.out.print(truthValue);
		System.out.print(": Passed ");
		System.out.println();       
        return true;
		
	}
	
	
	public void testIsValidPort() {

		
		System.out.println("Testing isValidPort(): ");

	
		assertTrue(callPortNumber(":0", true));
		assertTrue(callPortNumber(":80", true));
		assertTrue(callPortNumber(":800", true));	
		assertTrue(callPortNumber(":9000", true));
		assertTrue(callPortNumber(":65535", true));
		assertTrue(callPortNumber(":70000", true));
		assertTrue(callPortNumber(":-5", false));	
		assertTrue(callPortNumber(":80a", false));
		assertTrue(callPortNumber(":a23!", false));		
		
		System.out.println();	
};
        
		
	   static boolean incrementTestPartsIndex(int[] testPartsIndex, Object[] testParts) {
		      boolean carry = true;  //add 1 to lowest order part.
		      boolean maxIndex = true;
		     
		      
		      for (int testPartsIndexIndex = testPartsIndex.length - 1; testPartsIndexIndex >= 0; --testPartsIndexIndex) {

		    	  
		    	  int index = testPartsIndex[testPartsIndexIndex];
		           
		         ResultPair[] part = (ResultPair[]) testParts[testPartsIndexIndex];
		         if (carry) {
		            if (index < part.length - 1) {
		               index++;
		               testPartsIndex[testPartsIndexIndex] = index;
		                                        
		               carry = false;
		            } else {
		               testPartsIndex[testPartsIndexIndex] = 0;
		               carry = true;
		            }
		         }
		         
		         maxIndex &= (index == (part.length - 1));
		        

		      }

		      return (!maxIndex);
		   }
	
	   
	public void testIsValid() {
		UrlValidator uVal = new UrlValidator(null, null, UrlValidator.ALLOW_ALL_SCHEMES);

		assertTrue(uVal.isValid("http://www.google.com"));
	
	      
	      do {
	          StringBuffer testBuffer = new StringBuffer();
	          boolean expected = true;
	          for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) {
	             int index = testPartsIndex[testPartsIndexIndex];
	             ResultPair[] part = (ResultPair[]) testUrlParts[testPartsIndexIndex];
	             testBuffer.append(part[index].item);
	             expected &= part[index].valid;
	          }
	          //System.out.println(testPartsIndex[0]);
	          String url = testBuffer.toString();
	          boolean result = urlVal.isValid(url);
	          
	          
	         // if(result == true)
	         	// System.out.println(url);
	          assertEquals(url, expected, result);
	          	         
	       } while (incrementTestPartsIndex(testPartsIndex, testUrlParts));
	       if (printStatus) {
	          System.out.println();
	       }	

	}



	ResultPair[] testUrlScheme = { new ResultPair("http://", true),
			new ResultPair("ftp://", true), new ResultPair("h3t://", true),
			new ResultPair("3ht://", false), new ResultPair("http:/", false),
			new ResultPair("http:", false), new ResultPair("http/", false),
			new ResultPair("://", false), new ResultPair("", true) };

	ResultPair[] testUrlAuthority = { new ResultPair("www.google.com", true),
			new ResultPair("go.com", true), new ResultPair("go.au", true),
			new ResultPair("0.0.0.0", true),
			new ResultPair("255.255.255.255", true),
			new ResultPair("256.256.256.256", false),
			new ResultPair("255.com", true),
			new ResultPair("1.2.3.4.5", false),
			new ResultPair("1.2.3.4.", false), new ResultPair("1.2.3", false),
			new ResultPair(".1.2.3.4", false), new ResultPair("go.a", false),
			new ResultPair("go.a1a", false), new ResultPair("go.cc", true),
			new ResultPair("go.1aa", false), new ResultPair("aaa.", false),
			new ResultPair(".aaa", false), new ResultPair("aaa", false),
			new ResultPair("", false) };
	
	ResultPair[] testUrlPort = { new ResultPair(":80", true),};

	ResultPair[] testPath = { new ResultPair("/test1", true),
			new ResultPair("/t123", true), new ResultPair("/$23", true),
			new ResultPair("/..", false), new ResultPair("/../", false),
			new ResultPair("/test1/", true), new ResultPair("", true),
			new ResultPair("/test1/file", true),
			new ResultPair("/..//file", false),
			new ResultPair("/test1//file", false) };


	Object[] testUrlParts = { testUrlScheme, testUrlAuthority, testUrlPort,
			testPath, };
	int[] testPartsIndex = { 0, 0, 0, 0};

	ResultPair[] testScheme = { new ResultPair("http", true),
			new ResultPair("ftp", false), new ResultPair("httpd", false),
			new ResultPair("telnet", false) };



}
